package com.example.andoidepubziputil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.zip.ZipEntry;

import com.example.ParseXML.AsynParseXML;
import com.example.ParseXML.DefineContainer;
import com.example.ParseXML.DefinePackage;
import com.example.ParseXML.ParseContainer;
import com.example.ParseXML.ParsePackage;
import com.example.lib.AsynCollect;
import com.example.lib.AsynDecompress;
import com.example.lib.EpubUTIL;
import com.google.gson.Gson;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class Unzip extends Activity {

	TextView txt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_unzip);
		txt = (TextView) findViewById(R.id.txt);
		try {
			Bundle bundle = getIntent().getExtras();
			String URL = bundle.getString("EpubURL");
			Log.v("Path", URL);
			ZipEntry ze = null;

			// File file = new File(URL);
			// FileInputStream fos = new FileInputStream(file);

			String output = EpubUTIL.ROOT_LOCATION;

			new AsynDecompress(URL, output, Unzip.this, getLink_handler)
					.execute();
			// new AsynParseXML(Unzip.this,
			// getContainer_handler).execute(Environment.getExternalStorageDirectory().getAbsolutePath()+"/container.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.unzip, menu);
		return true;
	}

	public void ParseIt(String URL) {

		EpubUTIL.UNZIP_ROOT = URL + "/";
		EpubUTIL.UNZIP_container = EpubUTIL.UNZIP_ROOT
				+ "META-INF/container.xml";

		ParseContainer mcontainer = new ParseContainer(EpubUTIL.UNZIP_container);
		DefineContainer defineContainer = mcontainer.getContainer();

		EpubUTIL.UNZIP_package = EpubUTIL.UNZIP_ROOT
				+ defineContainer.getFull_path();
		
		ParsePackage parsePackage = new ParsePackage(EpubUTIL.UNZIP_package);
		DefinePackage definePackage = parsePackage.getPackage();
		
		
		txt.setText(EpubUTIL.UNZIP_package);

	}

	private Handler getLink_handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Bundle bundle = new Bundle();
				bundle = msg.getData();
				String kq = bundle.getString("link");
				ParseIt(kq);
				//txt.setText(kq);
			}
			super.handleMessage(msg);
		}

	};
}
